<?php


/** ensure this file is being included by a parent file */
defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );

/**
 * @package	
 */
class HelpDeskHTML 
{
	function selectOption( $value, $text='', $value_name='value', $text_name='text', $disable=false )
	{
		$obj = new stdClass;
		$obj->$value_name	= $value;
		$obj->$text_name	= trim( $text ) ? $text : $value;
		$obj->disable		= $disable;
		return $obj;
	}
	
	/**
	 * Generates just the option tags for an HTML select list
	 *
	 * @param	array	An array of objects
	 * @param	string	The name of the object variable for the option value
	 * @param	string	The name of the object variable for the option text
	 * @param	mixed	The key that is selected (accepts an array or a string)
	 * @returns	string	HTML for the select list
	 */
	function selectOptions( $arr, $key = 'value', $text = 'text', $selected = null, $translate = false )
	{
		$html = '';

		foreach ($arr as $i => $option)
		{
			$element =& $arr[$i]; // since current doesn't return a reference, need to do this

			$isArray = is_array( $element );
			$extra	 = '';
			if ($isArray)
			{
				$k 		= $element[$key];
				$t	 	= $element[$text];
				$id 	= ( isset( $element['id'] ) ? $element['id'] : null );
				if(isset($element['disable']) && $element['disable']) {
					$extra .= ' disabled="disabled"';
				}
			}
			else
			{
				$k 		= $element->$key;
				$t	 	= $element->$text;
				$id 	= ( isset( $element->id ) ? $element->id : null );
				if(isset( $element->disable ) && $element->disable) {
					$extra .= ' disabled="disabled"';
				}
			}

			// This is real dirty, open to suggestions,
			// barring doing a propper object to handle it
			if ($k === '<OPTGROUP>') {
				$html .= '<optgroup label="' . $t . '">';
			} else if ($k === '</OPTGROUP>') {
				$html .= '</optgroup>';
			}
			else
			{
				//if no string after hypen - take hypen out
				$splitText = explode( ' - ', $t, 2 );
				$t = $splitText[0];
				if(isset($splitText[1])){ $t .= ' - '. $splitText[1]; }

				//$extra = '';
				//$extra .= $id ? ' id="' . $arr[$i]->id . '"' : '';
				if (is_array( $selected ))
				{
					foreach ($selected as $val)
					{
						$k2 = is_object( $val ) ? $val->$key : $val;
						if ($k == $k2)
						{
							$extra .= ' selected="selected"';
							break;
						}
					}
				} else {
					$extra .= ( (string)$k == (string)$selected  ? ' selected="selected"' : '' );
				}

				//if flag translate text
				if ($translate) {
					$t = HelpDeskText::_( $t );
				}

				// ensure ampersands are encoded
				$k = HelpDeskFilterInput::ampReplace($k);
				$t = HelpDeskFilterInput::ampReplace($t);

				$html .= '<option value="'. $k .'" '. $extra .'>' . $t . '</option>';
			}
		}

		return $html;
	}

	/**
	 * Generates an HTML select list
	 *
	 * @param	array	An array of objects
	 * @param	string	The value of the HTML name attribute
	 * @param	string	Additional HTML attributes for the <select> tag
	 * @param	string	The name of the object variable for the option value
	 * @param	string	The name of the object variable for the option text
	 * @param	mixed	The key that is selected (accepts an array or a string)
	 * @returns	string	HTML for the select list
	 */
	function genericList( $arr, $name, $attribs = null, $key = 'value', $text = 'text', $selected = NULL, $idtag = false, $translate = false )
	{
		if ( is_array( $arr ) ) {
			reset( $arr );
		}

		if (is_array($attribs)) {
			$attribs = HelpDeskArrayHelper::toString($attribs);
		 }

		$id = $name;

		if ( $idtag ) {
			$id = $idtag;
		}

		$id		= str_replace('[','',$id);
		$id		= str_replace(']','',$id);

		$html	= '<select name="'. $name .'" id="'. $id .'" '. $attribs .'>';
		$html	.= HelpDeskHtml::selectOptions( $arr, $key, $text, $selected, $translate );
		$html	.= '</select>';

		return $html;
	}

	/**
	* Generates a select list of integers
	*
	* @param int The start integer
	* @param int The end integer
	* @param int The increment
	* @param string The value of the HTML name attribute
	* @param string Additional HTML attributes for the <select> tag
	* @param mixed The key that is selected
	* @param string The printf format to be applied to the number
	* @returns string HTML for the select list
	*/
	function integerList( $start, $end, $inc, $name, $attribs = null, $selected = null, $format = "" )
	{
		$start 	= intval( $start );
		$end 	= intval( $end );
		$inc 	= intval( $inc );
		$arr 	= array();

		for ($i=$start; $i <= $end; $i+=$inc)
		{
			$fi = $format ? sprintf( "$format", $i ) : "$i";
			$arr[] = HelpDeskHTML::selectOption(  $fi, $fi );
		}

		return HelpDeskHTML::genericList(   $arr, $name, $attribs, 'value', 'text', $selected );
	}

	/**
	* Generates an HTML radio list
	*
	* @param array An array of objects
	* @param string The value of the HTML name attribute
	* @param string Additional HTML attributes for the <select> tag
	* @param mixed The key that is selected
	* @param string The name of the object variable for the option value
	* @param string The name of the object variable for the option text
	* @returns string HTML for the select list
	*/
	function radioList( $arr, $name, $attribs = null, $key = 'value', $text = 'text', $selected = null, $idtag = false, $translate = false )
	{
		reset( $arr );
		$html = '';

		if (is_array($attribs)) {
			$attribs = HelpDeskArrayHelper::toString($attribs);
		 }

		$id_text = $name;
		if ( $idtag ) {
			$id_text = $idtag;
		}

		for ($i=0, $n=count( $arr ); $i < $n; $i++ )
		{
			$k	= $arr[$i]->$key;
			$t	= $translate ? HelpDeskText::_( $arr[$i]->$text ) : $arr[$i]->$text;
			$id	= ( isset($arr[$i]->id) ? @$arr[$i]->id : null);

			$extra	= '';
			$extra	.= $id ? " id=\"" . $arr[$i]->id . "\"" : '';
			if (is_array( $selected ))
			{
				foreach ($selected as $val)
				{
					$k2 = is_object( $val ) ? $val->$key : $val;
					if ($k == $k2)
					{
						$extra .= " selected=\"selected\"";
						break;
					}
				}
			} else {
				$extra .= ((string)$k == (string)$selected ? " checked=\"checked\"" : '');
			}
			$html .= "\n\t<input type=\"radio\" name=\"$name\" id=\"$id_text$k\" value=\"".$k."\"$extra $attribs />";
			$html .= "\n\t<label for=\"$id_text$k\">$t</label>";
		}
		$html .= "\n";
		return $html;
	}

	/**
	* Generates a yes/no radio list
	*
	* @param string The value of the HTML name attribute
	* @param string Additional HTML attributes for the <select> tag
	* @param mixed The key that is selected
	* @returns string HTML for the radio list
	*/
	function booleanList( $name, $attribs = null, $selected = null, $yes='yes', $no='no', $id=false )
	{
		$arr = array(
			HelpDeskHtml::selectOption( '0', HelpDeskText::_( $no ) ),
			HelpDeskHtml::selectOption( '1', HelpDeskText::_( $yes ) )
		);
		return HelpDeskHtml::radioList( $arr, $name, $attribs, 'value', 'text', (int) $selected, $id );
	}
	
	/**
	 * 
	 * @param $filename
	 * @param $path
	 * @param $mootools
	 * @return unknown_type
	 */
	function script( $filename, $path = 'media/system/js/', $mootools = true )
	{
		$src = JURI_COMPONENT_SITE.JURI_DS.$path.JURI_DS.$filename;
		echo "<script language='javascript' type='text/javascript' src='{$src}'></script>";
		return;
	}
	
	/**
	 * 
	 * @param $date
	 * @param $format
	 * @param $offset
	 * @return unknown_type
	 */
	function date($date, $format = null, $offset = NULL)
	{
		if ( ! $format ) {
			$format = HelpDeskText::_('DATE_FORMAT_LC1');
		}

		if(is_null($offset))
		{
			global $mosConfig_offset;
			$offset = $mosConfig_offset;
		}
		$instance = HelpDeskConfig::getDate($date);
		$instance->setOffset($offset);

		return $instance->toFormat($format);
	}
	
	/**
	 * 
	 * @param $i
	 * @param $id
	 * @return unknown_type
	 */
	function gridId( $rowNum, $recId, $checkedOut=false, $name='cid' )
	{
		if ( $checkedOut ) {
			return '';
		} else {
			return '<input type="checkbox" id="cb'.$rowNum.'" name="'.$name.'[]" value="'.$recId.'" onclick="isChecked(this.checked);" />';
		}	
	}
	
	/**
	 * 
	 * @param $row
	 * @param $i
	 * @param $imgY
	 * @param $imgX
	 * @param $prefix
	 * @return unknown_type
	 */
	function gridPublished( &$row, $i, $imgY = 'tick.png', $imgX = 'publish_x.png', $prefix='' )
	{
		$img 	= $row->published ? $imgY : $imgX;
		$task 	= $row->published ? 'unpublish' : 'publish';
		$alt 	= $row->published ? HelpDeskText::_( 'Published' ) : HelpDeskText::_( 'Unpublished' );
		$action = $row->published ? HelpDeskText::_( 'Unpublish Item' ) : HelpDeskText::_( 'Publish item' );

		$href = '
		<a href="javascript:void(0);" onclick="return listItemTask(\'cb'. $i .'\',\''. $prefix.$task .'\')" title="'. $action .'">
		<img src="images/'. $img .'" border="0" alt="'. $alt .'" /></a>'
		;

		return $href;
	}
	
	/**
	 * 
	 * @param $row
	 * @param $i
	 * @param $field
	 * @param $taskY
	 * @param $taskX
	 * @param $imgY
	 * @param $imgX
	 * @param $prefix
	 * @return unknown_type
	 */
	function gridCustom( &$row, $i, $field='published', $taskY='unpublish', $taskX='publish', $imgY = 'tick.png', $imgX = 'publish_x.png', $prefix='' )
	{
		$img 	= $row->$field ? $imgY : $imgX;
		$task 	= $row->$field ? $taskY : $taskN;
		$alt 	= $row->$field ? HelpDeskText::_( $taskY ) : HelpDeskText::_( $taskN );
		$action = $row->$field ? HelpDeskText::_( $taskN ) : HelpDeskText::_( $taskY );

		$href = '
		<a href="javascript:void(0);" onclick="return listItemTask(\'cb'. $i .'\',\''. $prefix.$task .'\')" title="'. $action .'">
		<img src="images/'. $img .'" border="0" alt="'. $alt .'" /></a>'
		;

		return $href;
	}
		
	/**
	 * 
	 * @param $rows
	 * @param $image
	 * @param $task
	 * @return unknown_type
	 */
	function gridOrder( $rows, $image='filesave.png', $task="saveorder" )
	{
		$alt = HelpDeskText::_( "Save Order" );
		$image = "<img src='images/{$image}' border='0' alt='{$alt}' /></a>"; 
		$href = '<a href="javascript:saveorder('.(count( $rows )-1).', \''.$task.'\')" title="'.HelpDeskText::_( 'Save Order' ).'">'.$image.'</a>';
		return $href;
	}
	
	/**
	 * sortList
	 */
	function sortList( $title, $order, $direction = 'asc', $selected = 0, $task=NULL ) 
	{
		global $mosConfig_live_site;
		
		// direction holds the way it is NOW
		$direction    = strtolower( $direction );

		if ($order == $selected ) {
			$newdirection    = ($direction == 'desc') ? 'asc' : 'desc';
		} else {
			$newdirection = "asc";
		}
		
		$html = '<a href="javascript:tableOrdering(\''.$order.'\',\''.$newdirection.'\',\''.$task.'\');" title="'.HelpDeskText::_( 'Sort' ).'">';
		$html .= $title;
	
		if ($order == $selected ) {
			if ($direction == "asc") { $html .= " <img src='".$mosConfig_live_site."/components/com_helpdesk/images/uparrow-1.png' border='none'>"; } 
			elseif ($direction == "desc") { $html .= " <img src='".$mosConfig_live_site."/components/com_helpdesk/images/downarrow-1.png' border='none'>"; } 
		}
	
		$html .= '</a>';
	
		return $html;
	}
	
	/**
	 * 
	 * @param $selector
	 * @param $params
	 * @return unknown_type
	 */
	function behaviorModal($selector='a.modal', $params = array())
	{
		static $modals;
		static $included;

		// $document =& JFactory::getDocument();

		// Load the necessary files if they haven't yet been loaded
		if (!isset($included)) {

			// Load the javascript and css
			// JHTML::script('modal.js');
			// JHTML::stylesheet('modal.css');

			$included = true;
		}

		if (!isset($modals)) {
			$modals = array();
		}

		$sig = md5(serialize(array($selector,$params)));
		if (isset($modals[$sig]) && ($modals[$sig])) {
			return;
		}

		// Setup options object
		$opt['ajaxOptions']	= (isset($params['ajaxOptions']) && (is_array($params['ajaxOptions']))) ? $params['ajaxOptions'] : null;
		$opt['size']		= (isset($params['size']) && (is_array($params['size']))) ? $params['size'] : null;
		$opt['onOpen']		= (isset($params['onOpen'])) ? $params['onOpen'] : null;
		$opt['onClose']		= (isset($params['onClose'])) ? $params['onClose'] : null;
		$opt['onUpdate']	= (isset($params['onUpdate'])) ? $params['onUpdate'] : null;
		$opt['onResize']	= (isset($params['onResize'])) ? $params['onResize'] : null;
		$opt['onMove']		= (isset($params['onMove'])) ? $params['onMove'] : null;
		$opt['onShow']		= (isset($params['onShow'])) ? $params['onShow'] : null;
		$opt['onHide']		= (isset($params['onHide'])) ? $params['onHide'] : null;

		$options = HelpDeskHtml::_getJSObject($opt);

		// Attach modal behavior to document
		echo "<script language='javascript' type='text/javascript'>";
		echo "
			window.addEvent('domready', function() {
	
				SqueezeBox.initialize(".$options.");
	
				$$('".$selector."').each(function(el) {
					el.addEvent('click', function(e) {
						new Event(e).stop();
						SqueezeBox.fromElement(el);
					});
				});
			});";
		echo "</script>";

		// Set static array
		$modals[$sig] = true;
		return;
	}
	

	/**
	 * Internal method to get a JavaScript object notation string from an array
	 *
	 * @param	array	$array	The array to convert to JavaScript object notation
	 * @return	string	JavaScript object notation representation of the array
	 * @since	1.5
	 */
	function _getJSObject($array=array())
	{
		// Initialize variables
		$object = '{';

		// Iterate over array to build objects
		foreach ((array)$array as $k => $v)
		{
			if (is_null($v)) {
				continue;
			}
			if (!is_array($v) && !is_object($v)) {
				$object .= ' '.$k.': ';
				$object .= (is_numeric($v) || strpos($v, '\\') === 0) ? (is_numeric($v)) ? $v : substr($v, 1) : "'".$v."'";
				$object .= ',';
			} else {
				$object .= ' '.$k.': '.HelpDeskHtml::_getJSObject($v).',';
			}
		}
		if (substr($object, -1) == ',') {
			$object = substr($object, 0, -1);
		}
		$object .= '}';

		return $object;
	}
	
}